package com.springboot.shanhexin.controller;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class loginCtrl {

    //跳转到登录页面
    @RequestMapping("/to_login")
    public String to_login() {
        return "houtai_login";
    }

    //退出登录,跳转到登录页面
    @RequestMapping("/down_login")
    public String down_login(HttpSession session, SessionStatus sessionStatus) {
        session.removeAttribute("username");
        System.out.print("1");
        System.out.print("1");
        return "houtai_login";
    }

    //登录验证
    @RequestMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String validateC = (String) request.getSession().getAttribute("checkcode");
        //从前台传来的用户输入的验证码
        String veryCode = request.getParameter("c");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        JSONObject jsonObject = new JSONObject();
        if (veryCode == null || "".equals(veryCode)) {
            jsonObject.put("code", "4");
            jsonObject.put("message","请输入验证码！");
            return jsonObject.toString();
        } else {
            if (validateC.equalsIgnoreCase(veryCode)) {
                int i = 0;
                if ("admin".equals(username) && "shanhexin123".equals(password)) {
                    i=1;
                }
                if (i > 0) {
                    HttpSession session = request.getSession();
                    session.setAttribute("username",username);
                    session.setAttribute("userid",i);
                    String usernameC = (String) request.getSession().getAttribute("username");
                    jsonObject.put("code", "1");
                    jsonObject.put("message", "登录成功");
                    return jsonObject.toString();
                }else {
                    jsonObject.put("code", "2");
                    jsonObject.put("message", "登录失败");
                    return jsonObject.toString();
                }

            } else {
                jsonObject.put("code", "3");
                jsonObject.put("message", "验证码错误");
                return jsonObject.toString();
            }
        }
    }

}
